package com.mo.modular.system.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mo.common.annotion.BussinessLog;
import com.mo.common.annotion.Permission;
import com.mo.common.constant.Const;
import com.mo.common.constant.Dict;
import com.mo.common.constant.cache.Cache;
import com.mo.common.constant.factory.ConstantFactory;
import com.mo.common.exception.BizExceptionEnum;
import com.mo.common.exception.BussinessException;
import com.mo.common.persistence.dao.OttImageMapper;
import com.mo.common.persistence.model.ImageParam;
import com.mo.common.persistence.model.OttImage;
import com.mo.config.properties.MoProperties;
import com.mo.core.base.controller.BaseController;
import com.mo.core.base.tips.Tip;
import com.mo.core.cache.CacheKit;
import com.mo.core.log.LogObjectHolder;
import com.mo.core.util.ThumbnailatorUtils;
import com.mo.core.util.ToolUtil;
import com.mo.modular.system.dao.ImageDao;
import com.mo.modular.system.warpper.ImageWarpper;

/**
 * 图片控制器
 *
 * @author chenxiaodong
 * @Date 2017年2月12日21:59:14
 */
@Controller
@RequestMapping("/image")
public class ImageController extends BaseController {

    private static String PREFIX = "/system/image";
    
    /**
     * 跳转到图片剪裁页面
     */
    @RequestMapping("/imagelist")
    public String imagelist() {
        return PREFIX + "/imagelist.html";
    }
    /**
     * 跳转到图片剪裁页面
     */
    @RequestMapping("/clipping")
    public String clipping() {
        return PREFIX + "/clipping.html";
    }
    /**
     * 跳转到图片剪裁页面
     */
    @RequestMapping("/compress")
    public String compress() {
    	ImageParam imageParam = new ImageParam();
    	try {
			ThumbnailatorUtils.clippingImg(imageParam);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return PREFIX + "/compress.html";
    }
    /**
     * 跳转到图片列表页面
     */
    @RequestMapping("/select")
    public String select() {
        return PREFIX + "/select.html";
    }

    @Resource
    private ImageDao ottImageDao;
    /**
     * 获取图片列表
     */
    @Permission
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String showName) {
    	Integer topLevel =0;
    	String urlMappingImgpath = MoProperties.getUrlMappingImgpath();
        List<Map<String, Object>> images = this.ottImageDao.selectImages(super.getPara("showName"),topLevel);
        return super.warpObject(new ImageWarpper(images,urlMappingImgpath));
    }
    /**
     * 跳转到添加图片
     */
   /* @RequestMapping(value = "/image_add")
    public String imageAdd() {
        return PREFIX + "/image_add.html";
    }*/


    @Resource
    private OttImageMapper ottImageMapper;
    /**
     * 跳转到修改图片
     */
    @Permission
    @RequestMapping(value = "/image_edit/{imageId}")
    public String imageEdit(@PathVariable Integer imageId, Model model) {
        if (ToolUtil.isEmpty(imageId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
//        OttImage ottImage = new OttImage();
        Map<String, Object> columnMap = new HashMap<String, Object>();
        columnMap.put("top_level", imageId);
        List<OttImage> ottImageList = this.ottImageMapper.selectByMap(columnMap);//(imageId);
        model.addAttribute("ottImageList",ottImageList);
        LogObjectHolder.me().set(ottImageList);
        return PREFIX + "/image_edit.html";
    }
    /**
     * 跳转到修改图片
     */
    @Permission
    @RequestMapping(value = "/image_clipping/{imageId}")
    public String imageClipping(@PathVariable Integer imageId, Model model) {
        if (ToolUtil.isEmpty(imageId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
//        OttImage ottImage = new OttImage();
        OttImage ottImage = this.ottImageMapper.selectById(imageId);
        model.addAttribute("ottImage",ottImage);
        LogObjectHolder.me().set(ottImage);
        return PREFIX + "/image_clipping.html";
    }
    /**
     * 图片新增
     */
    @RequestMapping(value = "/add")
    @BussinessLog(value = "添加图片", key = "name")
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public Tip add(@Valid ImageParam imageParam, BindingResult result) {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ToolUtil.isEmpty(imageParam)||ToolUtil.isEmpty(imageParam.getW())) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        OttImage ottImage = this.ottImageMapper.selectById(imageParam.getId());
        try {
        	imageParam.setSourceFileName(ottImage.getFileName());
        	imageParam.setTargetFileName(
        			ottImage.getFileName()
        				.substring(0,(ottImage.getFileName().length()-ottImage.getFileFormat().length()-1))
        				+ "-" + imageParam.getW() + "_" + imageParam.getH() + "." + imageParam.getFileFormat());
        	imageParam.setPath(ottImage.getFilePath());
			ThumbnailatorUtils.clippingImg(imageParam);
			String compressName = ottImage.getFileName()
        			.substring(0,(ottImage.getFileName().length()-ottImage.getFileFormat().length()-1))
        			+"-compress."+imageParam.getFileFormat();
			imageParam.setCompressName(compressName);
			ThumbnailatorUtils.compress(imageParam.getPath(), imageParam.getTargetFileName(), compressName);
			System.out.println(imageParam.getPath()+"--"+ottImage.getFileName());
			System.out.println(imageParam.getPath()+"--"+imageParam.getTargetFileName());
			
			File fileImg = new File(ottImage.getFilePath() + imageParam.getTargetFileName());
			ottImage.setSize(fileImg.length());
			fileImg = new File(ottImage.getFilePath() + imageParam.getCompressName());
			ottImage.setCompressSize(fileImg.length());
			ottImage.setId(null);
			ottImage.setCreateTime(new Date());
			ottImage.setModifyTime(new Date());
			ottImage.setFileName(imageParam.getTargetFileName());
			ottImage.setCompressName(compressName);
			ottImage.setTopLevel(imageParam.getId());
			ottImage.setResolution(imageParam.getW()+"*"+imageParam.getH());
			this.ottImageMapper.insert(ottImage);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return SUCCESS_TIP;
    }
    /**
     * 删除图片
     */
    @RequestMapping(value = "/remove")
    @ResponseBody
    public Tip remove(@RequestParam Integer ottImageId) {
        if (ToolUtil.isEmpty(ottImageId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        this.ottImageMapper.deleteById(ottImageId);//delOttImageById(ottImageId);
        //删除缓存
        CacheKit.removeAll(Cache.CONSTANT);
        return SUCCESS_TIP;
    }
    @RequestMapping(value = "/rotating")
    @ResponseBody
    public Tip rotating(@RequestParam Integer  angle,@RequestParam Integer ottImageId) {
        if (ToolUtil.isEmpty( angle)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        System.out.println(angle+"----"+ottImageId);
        OttImage ottImage = this.ottImageMapper.selectById(ottImageId);
        String[] resolution = ottImage.getResolution().split("\\*");
        try {
			ThumbnailatorUtils.rotatingImg(ottImage.getFilePath()+ottImage.getFileName(),Integer.parseInt(resolution[0]),Integer.parseInt(resolution[1]), angle);
		} catch (NumberFormatException e) {
			e.printStackTrace();
            throw new BussinessException(BizExceptionEnum.SERVER_ERROR);
			// TODO Auto-generated catch block
		} catch (IOException e) {
			e.printStackTrace();
            throw new BussinessException(BizExceptionEnum.SERVER_ERROR);
			// TODO Auto-generated catch block
		}
        //删除缓存
        CacheKit.removeAll(Cache.CONSTANT);
        return SUCCESS_TIP;
    }

    @Resource
    private MoProperties MoProperties;
    /**
     * 上传图片(上传到项目的webapp/static/img)
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public String upload(@RequestPart("file") MultipartFile picture) {
    	String fileRealName = picture.getOriginalFilename();
    	long size = picture.getSize();
    	String t = picture.getContentType();
    	String format = fileRealName.substring(fileRealName.lastIndexOf("."),fileRealName.length());
        String pictureName = UUID.randomUUID().toString() + format;//".jpg";
        String fileSavePath = MoProperties.getFileUploadPath();
        if(!fileSavePath.endsWith("/")){
        	fileSavePath += "/";
        }
        try {
			picture.transferTo(new File(fileSavePath + pictureName));
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        String resolution = "";
        BufferedImage bi;
		try {
			bi = ImageIO.read(new File(fileSavePath + pictureName));
			int width = bi.getWidth();
			int height = bi.getHeight();
			resolution = width+"*"+height;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
      //执行压缩
        String compressName = pictureName
    			.substring(0,(pictureName.length()-format.length()))
    			+"-compress."+format.substring(1);
        try {
			ThumbnailatorUtils.compress(fileSavePath, pictureName, compressName);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
            throw new BussinessException(BizExceptionEnum.UPLOAD_ERROR);
		}
		
		File fileImg = new File(fileSavePath + compressName);
		
        OttImage ottImage = new OttImage();
        ottImage.setCompressName(compressName);
        ottImage.setCompressSize(fileImg.length());
        
        ottImage.setCreateTime(new Date());
        ottImage.setModifyTime(new Date());
        ottImage.setFileFormat(format.substring(1));
        ottImage.setFileName(pictureName);
        ottImage.setFilePath(fileSavePath);
        ottImage.setResolution(resolution);
        ottImage.setShowName(fileRealName);
        ottImage.setSize(size);
        int id = ottImageMapper.insert(ottImage);
        System.out.println(id);
//        ottImageMapper.s
        return ottImage.getId()+"";
    }
   

}
